package com.lxn.filter;


import com.alibaba.fastjson.JSON;
import com.lxn.hrm.feignclients.RedisFeignClient;
import com.lxn.hrm.util.AjaxResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginCheckFilter extends ZuulFilter {


    @Autowired
    private RedisFeignClient redisFeignClient ;
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 1;
    }
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String requestURI = request.getRequestURI();

        if(requestURI.endsWith("/login") || requestURI.endsWith("/register")){
            return  false;
        }
        return true;
    }
    //登录检查
    @Override
    public Object run() throws ZuulException {
        //获取到请求头中的Token
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");
        //没有token
        if(!StringUtils.hasLength(token)){
            errorResponse();
            return null;
        }
        //有token,获取Redis中查询登录信息,集成Redis
        AjaxResult ajaxResult = redisFeignClient.get(token);
        if(!ajaxResult.isSuccess() || ajaxResult.getResultObj() == null){
            errorResponse();
        }
        return null;
    }
    private void errorResponse(){
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        currentContext.setSendZuulResponse(false);
        // 返回错误信息 AjaxResult
        AjaxResult ajaxResult = AjaxResult.me().setSuccess(false).setMessage("请登录!");

        try {
            response.getWriter().print(JSON.toJSONString(ajaxResult));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
